package peerToPeerFacebook.proj;

import java.io.Serializable;
import java.util.Observable;
import java.util.Observer;

/** Internal class that implements CallPending interface. This class should be returned when call can be pending
 * for a while. When the call is completed, one should call setResut to notify any waiting callers that call is done.
 */
public class CallPendingImpl extends Observable implements CallPending
{
    /** Result that should be returned to caller */
    protected Serializable result = null;
    
    /** Has the call completed */
    protected boolean completed = false;
    
    /** Is this exception or normal result? */
    protected boolean exception = false;
    
    /** Returns True if call has completed */
    @Override
    public boolean completed()
    {
        return completed;
    }

    /** Returns result for call. Only valid if completed is true. This method will throw if exception is set to
     * true 
     */
    @Override
    public Serializable result() throws Throwable
    {
        if (exception)
            throw (Throwable)result;
        
        return result;
    }   
    
    @Override
    public void addObserver(Observer o)
    {
        super.addObserver(o);
    }
    
    /** Sets results of this call and marks it as completed */
    public void setResult(Serializable result)
    {
        this.completed = true;
        this.exception = false;
        this.result = result;
        setChanged();
        notifyObservers();
    }
    
    /** Indicates that return value should we exception instead of regular return.
     * */
    public void setException(Throwable t)
    {
        this.completed = true;
        this.exception = true;
        this.result = t;
        setChanged();
        notifyObservers();
    }
}